const jwt = require("jsonwebtoken");
const { JWT_SECRET } = require("../config/config.default");
const {
  tokenExpiredError,
  invalidToken,
  tokenNotActive,
  hasNotAdminPermission,
} = require("../constants/err.type");

// 检测用户登录
const auth = async (ctx, next) => {
  const { authorization = "" } = ctx.request.header;
  const token = authorization.replace("Bearer ", "");
  try {
    //user中包含了payload 信息
    const user = jwt.verify(token, JWT_SECRET);

    ctx.state.user = user;
    await next();
  } catch (error) {
    switch (error.name) {
      case "TokenExpiredError":
        console.log("token已过期", error);
        return (ctx.body = tokenExpiredError);
      case "JsonWebTokenError":
        console.log("无效的token", error);
        return (ctx.body = invalidToken);
      case "NotBeforeError":
        console.log("token仍未生效", error);
        return (ctx.body = tokenNotActive);
      default:
        break;
    }
  }
};

// 是否是管理员
const hadAdminPermission = async (ctx, next) => {
  const { is_admin } = ctx.state.user;
  if (!is_admin) {
    console.error("该用户没有管理员权限", ctx.state.user);
    return ctx.app.emit("error", hasNotAdminPermission, ctx);
  }
  await next();
};

module.exports = {
  auth,
  hadAdminPermission,
};
